package com.amphora.services.crud.impl;

import com.amphora.model.Category;
import com.amphora.services.crud.CategoryService;
import com.amphora.util.exceptions.CRUDExceptions;
import com.amphora.util.factories.DomainFactory;
import com.amphora.util.repository.JPAUtil;

public class CategoryServiceImpl implements CategoryService{

	@Override
	public void createCategory(String name,String description) throws CRUDExceptions {
		Category newCategory = DomainFactory.getCategory(name, description);
		JPAUtil.createEntity(newCategory);
		
		if(JPAUtil.findById(Category.class, newCategory.getId())==null){
			throw new CRUDExceptions("Error: There was a error while creating the category");
		}
	}

	@Override
	public void updateCategory(Category categoryToUpdate) throws CRUDExceptions{
		// TODO Auto-generated method stub
		Category categoryToBeUpdated = JPAUtil.findById(Category.class, categoryToUpdate.getId());
		
		if(JPAUtil.findById(Category.class, categoryToUpdate.getId())==null)
			throw new CRUDExceptions("Error: There was a error while reading the category from the database");
		
		JPAUtil.update(Category.class, categoryToBeUpdated.getId());
		
	}

	@Override
	public void deleteCategory(Long categoryId) throws CRUDExceptions{
		// TODO Auto-generated method stub
		Category categoryToBeDeleted = JPAUtil.findById(Category.class, categoryId);
		
		if(JPAUtil.findById(Category.class, categoryToBeDeleted.getId())==null)
			throw new CRUDExceptions("Error: There was a error while reading the category from the database");
		
		JPAUtil.delete(categoryToBeDeleted);
		
		if(JPAUtil.findById(Category.class, categoryToBeDeleted.getId())!=null)
			throw new CRUDExceptions("Error: There was a error while deleting the category from the database");
	}

}
